package com.fuyao.cloud.common.data.resolver;

import cn.hutool.core.util.StrUtil;
import com.fuyao.cloud.admin.api.feign.RemoteDictItemService;
import com.fuyao.cloud.common.core.util.DictItemOption;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.core.util.SpringContextHolder;
import lombok.experimental.UtilityClass;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author cloud
 * @date 2020/5/12
 * <p>
 * 字典配置解析器
 */
@UtilityClass
public class DictItemResolver {

	/**
	 * 根据字典类型获取字典项集合
	 * @param type 字典类型
	 * @return 字典项信息
	 */
	public R<Map<String,List<DictItemOption>>> getDictItemType(String type){
		RemoteDictItemService remoteDictItemService = SpringContextHolder.getBean(RemoteDictItemService.class);
		return remoteDictItemService.getDictItemByType(type);
	}

	/**
	 * 根据字典类型获取字典项集合
	 * @param types 字典类型集合
	 * @return 字典项信息
	 */
	public R<Map<String,List<DictItemOption>>> getDictItemTypeList(List<String> types){
		RemoteDictItemService remoteDictItemService = SpringContextHolder.getBean(RemoteDictItemService.class);
		return remoteDictItemService.getDictItemList(types);
	}

	/**
	 * 获取单个类型字典可选项map
	 * @return 字典map。
	 */
	public static Map<String,List<DictItemOption>> getDictOptionResultMap(String type){
		// 查询字典信息
		R<Map<String, List<DictItemOption>>> result = DictItemResolver.getDictItemTypeList(Collections.singletonList(type));
		return result.getData();
	}

	/**
	 * 获取多个字典可选项map
	 * @return 字典map。
	 */
	public static Map<String,List<DictItemOption>> getDictOptionResultMap(String [] types){
		// 查询字典信息
		List<String> dictOptionTypes = Arrays.asList(types);
		R<Map<String, List<DictItemOption>>> result = DictItemResolver.getDictItemTypeList(dictOptionTypes);
		return result.getData();
	}

	/**
	 * 获取字典标签值
	 * @param options 字典集合
	 * @param value value
	 * @return label
	 */
	public static String getDictOptionValue(List options,String value){
		if(checkValue(value)){
			return value;
		}
		for (Object option : options) {
			if(option instanceof DictItemOption){
				DictItemOption dictItemOption =  (DictItemOption)option;
				if(value.equals(dictItemOption.getLabel())){
					return dictItemOption.getValue();
				}
			}
		}
		return value;
	}

	/**
	 * 获取字典标签名称
	 * @param options 字典集合
	 * @param value value
	 * @return label
	 */
	public static String getDictOptionLabel(List options,String value){
		if(checkValue(value)){
			return value;
		}
		for (Object option : options) {
			if(option instanceof DictItemOption){
				DictItemOption dictItemOption =  (DictItemOption)option;
				if(value.equals(dictItemOption.getValue())){
					return dictItemOption.getLabel();
				}
			}
		}
		return value;
	}

	private boolean checkValue(String value){
		return StrUtil.isEmpty(value);
	}
}
